﻿using System;

class ExchangeRandomBits
{
    static void Main()
    {
        int number;
        int bitPositionP;
        int bitPositionQ;
        int numberOfBitsToChange;

        Console.WriteLine("Type a number:");
        bool isNumberValid = int.TryParse(Console.ReadLine(), out number);
        Console.WriteLine("Type bit position p:");
        bool isBitPositionPValid = int.TryParse(Console.ReadLine(), out bitPositionP);
        Console.WriteLine("Type bit position q:");
        bool isBitPositionQValid = int.TryParse(Console.ReadLine(), out bitPositionQ);
        Console.WriteLine("Number of bits to change k:");
        bool isNumberOfBitsValid = int.TryParse(Console.ReadLine(), out numberOfBitsToChange);

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        if (isNumberValid && isBitPositionPValid && isBitPositionQValid && bitPositionP < (29) && bitPositionQ < (29))
        {
            string binaryInReverse = Convert.ToString(number, 2).PadLeft(32, '0');
            string binary = "";
            Console.WriteLine("Number as binary is:{0}", binaryInReverse);
            for (int i = 0; i < binaryInReverse.Length; i++)
            {
                binary = binaryInReverse[i] + binary;
            }

            char[] exchangedBitsNumberInReverse = binary.ToCharArray();

            for (int i = 0; i < numberOfBitsToChange; i++)
            {
                exchangedBitsNumberInReverse[bitPositionP + i] = binary[bitPositionQ + i];
            }

            string exchangedBitsNumber = "";

            for (int i = 0; i < binaryInReverse.Length; i++)
            {
                exchangedBitsNumber = exchangedBitsNumberInReverse[i] + exchangedBitsNumber;
            }

            number = Convert.ToInt32(exchangedBitsNumber, 2);
            Console.WriteLine("Number as binary is:{0}", exchangedBitsNumber);
            Console.WriteLine("And as decimal is:{0}", number);
        }
        else
        {
            Console.WriteLine("Your input isn`t OK!!!");
        }

        stopwatch.Stop();
        Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
    }
}